<template>
    <div class="container p-5 shadow mt-3">
        <table class="table">
            <thead>
                <tr>
                    <th scope="col" class="table-dark"></th>
                    <th scope="col" class="table-dark">商品名称</th>
                    <th scope="col" class="table-dark">商品单价(元/台)</th>
                    <th scope="col" class="table-dark">数量(台)</th>
                    <th scope="col" class="table-dark">操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in data" :key="item.id">
                    <th scope="row">{{ item.id }}</th>
                    <td>{{ item.name }}</td>
                    <td>{{ item.price }}</td>
                    <td>
                        <button type="button" class="btn btn-outline-danger"
                            @click="handlerCount($event, -1, item.id)">-</button>
                        {{ item.num }}
                        <button type="button" class="btn btn-outline-success"
                            @click="handlerCount($event, 1, item.id)">+</button>
                    </td>
                    <td>
                        <button type="button" class="btn btn-outline-danger" @click="del($event, item.id)">删除</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <h2>
            总计: {{ total }} 元
        </h2>
    </div>
</template>

<script setup>
import { computed, ref } from "vue";

const data = ref([{
    id: 1,
    name: "iphone X",
    price: 7999,
    num: 1
},
{
    id: 2,
    name: "荣耀",
    price: 2399,
    num: 1
},
{
    id: 3,
    name: "华为",
    price: 3399,
    num: 1
},
{
    id: 4,
    name: "小米",
    price: 3999,
    num: 1
}])

const del = (e, _id) => {
    data.value = data.value.filter(item => item.id != _id)
}
const handlerCount = (e, _count, _id) => {
    data.value.forEach(item => {
        if (item.id == _id) {
            if (_count < 0 && item.num > 0) --item.num;
            else if (_count > 0) ++item.num;
        }
    });
}

const total = computed(()=>{
    return data.value.reduce((acc, item) => acc + (item.price * item.num), 0)
})

</script>

<style scoped></style>